from binance.client import Client
import pandas as pd
import mplfinance as mpf
from tdx import  Zhibiao

proxies = {
    'http': 'socks5://127.0.0.1:10010',
    'https': 'socks5://127.0.0.1:10010',
}

apiKey = "ZtrfFQwYrPs7qyZlsEgP1tIPwwEX0GAyyLRHI0bQ2oOvOmMZjGs9SSHTy8MEko6Y"
secrets = "GGuSQdyuU33r3q3EPZ3TXVmASd1sr0chlskeO7e96iP5hQx11lT4MWb76UqOjc39"

# 初始化币安客户端
client = Client(requests_params={'proxies': proxies, 'timeout': 10},api_key=apiKey,api_secret=secrets)


# 获取K线数据（BTC/USDT 1小时数据，最近500根）
klines = client.futures_klines(symbol="BTCUSDT", interval="5m", limit=200)

# 转换为DataFrame
df = pd.DataFrame(klines, columns=[
    "timestamp", "open", "high", "low", "close", "volume",
    "close_time", "quote_asset_volume", "trades",
    "taker_buy_base", "taker_buy_quote", "ignore"
])

# 转换数据类型

df = df[["timestamp", "open", "high", "low", "close", "volume"]].astype(float)
df["timestamp"] = pd.to_datetime(df["timestamp"], unit="ms")
df.set_index("timestamp", inplace=True)

# 计算RSI（14日周期）
def calculate_rsi(close, window=14):
    delta = close.diff()
    gain = delta.clip(lower=0)
    loss = -delta.clip(upper=0)
    avg_gain = gain.rolling(window).mean()
    avg_loss = loss.rolling(window).mean()
    rs = avg_gain / avg_loss
    return 100 - (100 / (1 + rs))

df["RSI"] = calculate_rsi(df["close"])
rsi12 = calculate_rsi(df["close"],12)

fxxs,buy = Zhibiao.ths_chaodi(df)
print(fxxs)
# 创建副图对象
apds = [
    mpf.make_addplot(
        df["RSI"],
        panel=1,                # 在第1个副图绘制
        color="purple",
        ylabel="RSI (14)",
        linestyle="--",
        alpha=0.8
    ),
    mpf.make_addplot(
        rsi12,
        panel=1,  # 在第1个副图绘制
        color="red",
        ylabel="RSI (14)",
        linestyle="--",
        alpha=0.8
    ),
    mpf.make_addplot(
        fxxs,
        panel=2,  # 在第1个副图绘制
        color="red",
        ylabel="RSI (14)",
        linestyle="-",
        alpha=0.8
    ),
    mpf.make_addplot([70]*len(df), panel=1, color="red", linestyle="-"),  # 超买线
    mpf.make_addplot([30]*len(df), panel=1, color="green", linestyle="-"), # 超卖线

    mpf.make_addplot([80] * len(df), panel=2, color="red", linestyle="-"),  # 超买线
    mpf.make_addplot([20] * len(df), panel=2, color="green", linestyle="-")  # 超卖线
]

# 绘制图表
mpf.plot(
    df,
    type="candle",
    style="binance",
    addplot=apds,
    panel_ratios=(3, 1),       # 主图:副图高度比=3:1
    volume=True,
    title="BTC/USDT 1h K线 + RSI",
    figscale=1.2
)
